package com.shanxia.codec.cmd;

import com.shanxia.codec.ProtocolDataBase;
import com.shanxia.codec.enums.DecodeEnum;
import com.shanxia.codec.enums.ModuleWarningEnum;
import com.shanxia.codec.enums.SystemWarningEnum;
import lombok.Data;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import static com.shanxia.codec.Decoder.*;

/**
 * C -> S
 * 充电桩告警信息上报
 * 充电桩告警信息
 */
@Data
public class Cmd108 extends ProtocolDataBase {

    public static final int MIN_SIZE = 68;

    private int v1;
    private int v2;
    private String sn;                                  // 充电桩编码
    private List<SystemWarningEnum> systemWarnings;     // 告警信息

    public Cmd108(){
        super.setCmd(108);
    }

    public static Cmd108 decodeFromBase(ProtocolDataBase protocolDataBase) {
        Cmd108 cmd = new Cmd108();
        cmd.copyDataFrom(protocolDataBase);
        byte[] dataField = protocolDataBase.getDataField();
        if (dataField.length < MIN_SIZE) {
            cmd.setResult(DecodeEnum.InvalidData);
            return cmd;
        }
        int offset = 0;
        cmd.v1 = getUint16(dataField, offset);
        offset += 2;
        cmd.v2 = getUint16(dataField, offset);
        offset += 2;
        // 32字节充电桩编码
        cmd.sn = byteToAscii(Arrays.copyOfRange(dataField, offset, offset + 32), true);
        offset += 32;
        // 32字节告警
        List<SystemWarningEnum> warnings = new ArrayList<>(32);
        for (int i = 1; i <= 32; i ++) {
            byte value = dataField[offset++];
            for (int b = 0; b < 8; b ++) {
                if (Objects.equals(getBits(value, b, 1), 1)) {
                    warnings.add(SystemWarningEnum.getByPos(i, b));
                }
            }
        }
        cmd.systemWarnings = warnings;
        return cmd;
    }

    @Override
    public String toString() {

        StringBuffer buffer = new StringBuffer();
        buffer.append("#cmd108#").append("\n");
        buffer.append("v1:").append(v1).append("\n");
        buffer.append("v2:").append(v2).append("\n");
        buffer.append("充电桩编码:").append(sn).append("\n");
        buffer.append("告警信息:【").append("\n");
        for(SystemWarningEnum systemWarningEnum : systemWarnings){
            buffer.append(systemWarningEnum.descr).append("\n");
        }
        buffer.append("】").append("\n");
        return buffer.toString();
    }
}
